<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import {ref} from "vue";
import {deleteCheckArea, fetchGetAllCategory, fetchGetCheckAreaList} from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import {enableStatusRecord} from '@/constants/business';
import { useTable, useTableOperate } from '@/hooks/common/table';
import AreaOperateDrawer from './modules/area-operate-drawer.vue';
// import UserSearch from './modules/hosp-search.vue';
const appStore = useAppStore();
const CategoryOptions = ref<CommonType.Option<string>[]>([]);
async function getCategoryOptions() {
  const { error, data } = await fetchGetAllCategory();
  if (!error) {
    const options = data.map(item => ({
      label: item.name,
      value: item.id
    }));
    CategoryOptions.value = [...options];
  }
}
const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  immediate: undefined,
  apiFn: async (...args) => {
    // 在加载表格数据之前，刷新分类数据
    await getCategoryOptions();
    // 然后加载表格数据
    const response = await fetchGetCheckAreaList(...args);
    return response;
  },
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: $t('common.index'),
      align: 'center',
      width: 64
    },
    {
      key: 'categoryId',
      title: $t('page.check.area.categoryId'),
      align: 'center',
      width: 100,
      render: (row) => {
        // 从 CategoryOptions 中查找对应的分类名称
        const category = CategoryOptions.value.find(option => option.value === row.categoryId);
        return category ? category.label : $t('common.unknown'); // 如果找不到，显示“未知”
      }
    },
    {
      key: 'name',
      title: $t('page.check.area.name'),
      align: 'center',
      width: 100
    },
    {
      key: 'standard',
      title: $t('page.check.area.standard'),
      align: 'center',
      width: 100,
    },
    {
      key: 'createBy',
      title: $t('page.check.area.createBy'),
      align: 'center',
      width: 100,
    },
    {
      key: 'score',
      title: $t('page.check.area.score'),
      align: 'center',
      width: 100
    },
    {
      key: 'scoringMethod',
      title: $t('page.check.area.scoringMethod'),
      align: 'center',
      width: 100
    },
    {
      key: 'deficiencyScore',
      title: $t('page.check.area.deficiencyScore'),
      align: 'center',
      width: 100
    },
    {
      key: 'remark',
      title: $t('page.check.area.remark'),
      align: 'center',
      width: 100
    },
    {
      key: 'isusing',
      title: $t('page.check.area.isusing'),
      align: 'center',
      width: 100,
      render: row => {
        console.log(row);
        if (row.isusing === null) {
          return null;
        }
        const tagMap: Record<Api.Common.EnableStatus, NaiveUI.ThemeColor> = {
          1: 'success',
          0: 'warning'
        };
        const label = $t(enableStatusRecord[row.isusing]);
        return <NTag type={tagMap[row.isusing]}>{label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  console.log(checkedRowKeys.value);

  onBatchDeleted();
}

async function handleDelete(id: string) {
  let response;
  try {
    // 调用删除 API
    response = await deleteCheckArea(id);

    // 删除成功后的提示
    // message.success('删除成功');
    console.log(response);
    // 根据接口返回结果处理
    if (response.error) {
      window.$message?.error($t('common.operationFailed'));
      return;
    }
    // 提示成功
    window.$message?.success($t('common.DeleteSuccess'));
    // 调用父组件或其他逻辑更新数据
    onDeleted();
  } catch (error) {
    // 删除失败的提示
    console.error('删除失败:', error);
  }
}

function edit(id: string) {
  handleEdit(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage"/>
    <NCard :title="$t('page.check.area.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <AreaOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
